package cn.rengy.tool.core.util;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 异常重试工具类
 */
public class  RetryUtils{
	private static Logger logger = LoggerFactory.getLogger(RetryUtils.class);
	
	/**
	 * 回调结果检查
	 */
	public interface ResultCheck {
		boolean matching();
	}
	
	/**
	 * 在遇到异常时尝试重试
	 * @param retryLimit 重试次数
	 * @param retryCallable 重试回调
	 * @return V
	 */
	public static <V extends ResultCheck> V retryOnException(int retryLimit,
			java.util.concurrent.Callable<V> retryCallable) {

		V v = null;
		for (int i = 0; i < retryLimit; i++) {
			try {
				v = retryCallable.call();
				if (v.matching()) break;
			} catch (Exception e) {
			}
		}
		return v;
	}
	/*return RetryUtils.retryOnException(3, new Callable<SnsAccessToken>() {
        
        @Override
        public SnsAccessToken call() throws Exception {
            String json = HttpUtils.get(url, queryParas);
            return new SnsAccessToken(json);
        }
    });*/
	ExecutorService exec=Executors.newFixedThreadPool(10);
	public <T> void submitAsyn(Callable<T> call, CompletionHandler<? super T> handler) throws Exception {
		
		exec.execute(new Runnable(){
			public void run(){
				try {
					handler.completed( call.call());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	//异步调用的例子
//	ExecutorService exec=Executors.newFixedThreadPool(10);
//	public <T> void sendSmsAsyn(final String content, final List<String> mobileList,Callable<T> callBack)  {
//		exec.execute(new Runnable() {
//			public T run() {
//				return callBack.call();
//			}
//		});
//	}
//	
//	public void sendSmsAsyn(final String content, final List<String> mobileList,final SmsCallBack callBack)  {
//		exec.execute(new Runnable() {
//			public void run() {
//					SendResult sr  = sendSms(content, mobileList);
//					if(null != callBack ){
//						callBack.callback(sr);
//					}
//			}
//		});
//	}
	
}
